<template>
  <xn-form-container
    :title="formData.ID ? '编辑部门信息' : '新增部门信息'"
    :width="500"
    :visible="visible"
    :destroy-on-close="true"
    @close="onClose"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="上级部门" name="PDeptID">
        <a-tree-select
          v-model:value="formData.PDeptID"
          style="width: 100%"
          placeholder="请选择上级部门"
          :tree-line="true"
          :tree-data="treeData"
          tree-node-filter-prop="title"
          :fieldNames="replaceFields"
        >
          <!--  <template #title="{ value: val, title }">
            <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
            <template v-else>{{ title }}</template>
          </template> -->
        </a-tree-select>
      </a-form-item>
      <a-form-item label="部门名称" name="DeptName">
        <a-input
          v-model:value="formData.DeptName"
          placeholder="请输入部门名称"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="部门说明" name="DeptDesp">
        <a-input
          v-model:value="formData.DeptDesp"
          placeholder="请输入部门说明"
          allow-clear
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button class="xn-mr8 mr10" @click="onClose">关闭</a-button>
      <a-button type="primary" @click="onSubmit">{{
        formData.ID ? "确认修改" : "确认新增"
      }}</a-button>
    </template>
  </xn-form-container>
</template>

<script setup>
import { required } from "@/utils/formRules";
import deptmgrApi from "@/api/systemManagement/deptmgrApi";
import { ref, onMounted, watch } from "vue";
import XnFormContainer from "@/components/XnFormContainer/index.vue";
import { message } from "ant-design-vue";

// 默认是关闭状态
const visible = ref(false);
const emit = defineEmits({ successful: null });
const formRef = ref();

// 表单数据
const formData = ref({});
// 打开抽屉
const onOpen = (record) => {
  visible.value = true;
  if (record) {
    formData.value = Object.assign({}, record);
  } else {
    formData.value = {};
  }
};
// 关闭抽屉
const onClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};

// 默认要校验的
const formRules = {
  PDeptID: [required("请选择上级部门")],
  DeptName: [required("请输入部门名称")],
  DeptDesp: [required("请输入部门说明")],
};

// 验证并提交数据
const onSubmit = () => {
  // 有id为编辑,无id为新增
  if (!formData.value.ID) {
    formRef.value
      .validate()
      .then(() => {
        deptmgrApi
          .addDept({
            PDeptID: formData.value.PDeptID,
            DeptName: formData.value.DeptName,
            DeptDesp: formData.value.DeptDesp,
          })
          .then(() => {
            message.success("新增成功");
            onClose();
            emit("successful");
          });
      })
      .catch(() => {});
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      deptmgrApi
        .modifyDept({
          ID: formData.value.ID,
          PDeptID: formData.value.PDeptID,
          DeptName: formData.value.DeptName,
          DeptDesp: formData.value.DeptDesp,
        })
        .then(() => {
          message.success("修改成功");
          onClose();
          emit("successful");
        });
    })
    .catch(() => {});
};

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
  onOpen,
});
// 请求最新的部门数据,用来选择上级部门
let treeData = ref([
  {
    ID: 0,
    PID: 0,
    DeptName: "顶级",
  },
]);
const fetchData = () => {
  treeData.value = [
    {
      ID: 0,
      PID: 0,
      DeptName: "顶级",
    },
  ];
  deptmgrApi
    .getDepts({
      ID: 0,
      PID: 0,
      DeptName: "",
    })
    .then((res) => {
      let data = res.Data;
      transformTreeData(data);
      data.forEach((item) => {
        treeData.value.push(item);
      });
      
    });
};
// 监听是否打开了抽屉,如果是则请求数据,用来选择上级部门
watch(
  () => visible.value,
  (n, o) => {
    if (n) {
      fetchData();
    }
  }
);
const replaceFields = {
  children: "Childs",
  label: "DeptName",
  key: "ID",
  value: "ID",
};
// 转换数据,把当前编辑的数据从可选的上级部门中删除掉,防止选择到自己本身作为上级部门
const transformTreeData = (data) => {
  for (let i = 0; i < data.length; i++) {
    if (data[i].ID === formData.value.ID) {
      data.splice(i, 1);
      break;
    } else if (data[i].Childs) {
      transformTreeData(data[i].Childs);
    }
  }
};
</script>
